package com.zjj.distributed.zk.client;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;

/**
 * @author zhanglei.zjj
 * @description Zookeeper官方客户端，基本操作
 * @date 2023/6/18 17:04
 */
@Slf4j
public class BaseOperations extends StandaloneBase {
    @Test
    public void createTest() throws KeeperException, InterruptedException {
        String path = zooKeeper.create("/javaClient/sync", "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        log.info("created path: {}", path);
    }

    @Test
    public void createAsycTest() throws InterruptedException {
        zooKeeper.create("/javaClient/async", "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT,
                (rc, path, ctx, name) -> {
                    log.info("rc: {}, path: {}, ctx: {}, name: {}", rc, path, ctx, name);
                    processCtl.countDown();
                }, "context");
        processCtl.await();
    }

    @Test
    public void setTest() throws KeeperException, InterruptedException {

        Stat stat = new Stat();
        byte[] data = zooKeeper.getData("/javaClient/async", false, stat);
        log.info("修改前: {}", new String(data));

        // 带版本号的更新，如果传-1 代表无条件更新
        zooKeeper.setData("/javaClient/async", "changed!".getBytes(), stat.getVersion());
        byte[] dataAfter = zooKeeper.getData("/javaClient/async", false, stat);
        log.info("修改后: {}", new String(dataAfter));
    }

    @Test
    public void testGetData() throws InterruptedException {

        Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getPath() != null && event.getPath().equals("/javaClient/async")
                        && event.getType() == Event.EventType.NodeDataChanged) {
                    log.info(" PATH: {}  发现变化", "/javaClient/async");
                    try {
                        byte[] data = getZooKeeper().getData("/javaClient/async", this, null);
                        log.info(" data: {}", new String(data));
                    } catch (KeeperException | InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        try {
            byte[] data = getZooKeeper().getData("/javaClient/async", watcher, null);  //
            log.info(" data: {}", new String(data));
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }

        Thread.sleep(Integer.MAX_VALUE);
    }

    @Test
    public void testDelete() throws KeeperException, InterruptedException {
        String path = zooKeeper.create("/javaClient/dTest1", "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

        // -1 代表匹配所有版本，直接删除
        // 任意大于 -1 的代表可以指定数据版本删除
        getZooKeeper().delete(path, -1);

    }
}
